const http = require('http')
const path = require('path')
const server = http.createServer()

const fse = require('fs-extra') // fs文件扩展模块api
const multiparty = require('multiparty') // 解析FormData数据的一款插件
const streamUtil = require('./util/stream')

// 大文件存储目录
const upload_dir = path.resolve(__dirname, 'target')

// sream 流合并：https://www.cnblogs.com/goloving/p/12825973.html

server.on('request', async (req, res) => {
  const fileName = ''
  // req.url 是客户端请求的 URL 地址
  const url = req.url
  // req.method 是客户端请求的 method 类型
  const method = req.method
  const str = `Your request url is ${url}, and request method is ${method}`
  console.log(str)

  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Methods', '*')
  if (req.method === 'OPTIONS') {
    res.status = 200
    res.end()
    return
  }

  if (url === '/merge') {
    const data = await streamUtil.resolvePost(req)
    console.log('merge ->', data)
    const { fileName, size } = data
    const targetPath = path.resolve(upload_dir, `${fileName}`)
    console.log('写入的目标文件 -> ', targetPath)

    const chunkDir = path.resolve(upload_dir, 'chunkDir' + '_' + fileName)
    // streamUtil.mergeChunks(chunkDir, targetPath, () => {
    //   streamUtil.clearDirAndFiles(chunkDir) // 删除目录以及目录下文件
    // })
    streamUtil.mergeFileChunk(chunkDir, targetPath, size)

    res.end(
      JSON.stringify({
        code: 0,
        message: 'file merged success'
      })
    )
  }

  // 生成multiparty对象，并配置上传目标路径
  // var form = new multiparty.Form({uploadDir: './upload/picture/'});
  const multipart = new multiparty.Form()

  multipart.parse(req, async (err, fields, files) => {
    // console.log('文件解析：multipart.parse')
    // console.log('err -> ', err)
    // console.log('fields -> ', fields)
    // console.log('files -> ', files)
    if (err) return

    const [chunk] = files.chunk
    const [hash] = fields.hash
    const [filename] = fields.filename ? fields.filename : fileName

    // 创建临时目录用于临时存储chunk
    // 添加chunkDir 前缀与文件名做区分
    const chunkDir = path.resolve(upload_dir, 'chunkDir' + '_' + filename)

    if (!fse.exists(chunkDir)) {
      console.log('创建临时存储chunk目录：', chunkDir)
      fse.mkdir(chunkDir)
    }

    // fs-extra 的 rename 方法 windows 平台会有权限问题
    // @see https://github.com/meteor/meteor/issues/7852#issuecomment-255767835
    await fse.move(chunk.path, `${chunkDir}/${hash}`)
    res.end('received file chunk')
  })
})

server.listen(3001, () => {
  console.log('listening on port 3001')
})
